package org.zheng.shop.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zheng.shop.dto.CarouselDTO;
import org.zheng.shop.entity.Carousel;
import org.zheng.shop.repository.CarouselRepository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 轮播图服务类
 */
@Service
@Transactional
public class CarouselService {
    
    @Autowired
    private CarouselRepository carouselRepository;
    
    /**
     * 获取所有启用的轮播图（前端展示用）
     */
    public List<CarouselDTO> getEnabledCarousels() {
        List<Carousel> carousels = carouselRepository.findByIsEnabledTrueOrderBySortOrderAsc();
        return carousels.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 获取所有轮播图（管理后台用）
     */
    public List<CarouselDTO> getAllCarousels() {
        List<Carousel> carousels = carouselRepository.findAllByOrderBySortOrderAsc();
        return carousels.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据ID获取轮播图
     */
    public CarouselDTO getCarouselById(Long id) {
        Optional<Carousel> carousel = carouselRepository.findById(id);
        return carousel.map(this::convertToDTO).orElse(null);
    }
    
    /**
     * 创建轮播图
     */
    public CarouselDTO createCarousel(CarouselDTO carouselDTO, Integer createdBy) {
        Carousel carousel = new Carousel();
        carousel.setTitle(carouselDTO.getTitle());
        carousel.setDescription(carouselDTO.getDescription());
        carousel.setImageUrl(carouselDTO.getImageUrl());
        carousel.setLinkUrl(carouselDTO.getLinkUrl());
        
        // 如果没有指定排序顺序，设置为最大值+1
        if (carouselDTO.getSortOrder() == null) {
            Integer maxOrder = carouselRepository.findMaxSortOrder();
            carousel.setSortOrder(maxOrder + 1);
        } else {
            carousel.setSortOrder(carouselDTO.getSortOrder());
        }
        
        carousel.setIsEnabled(carouselDTO.getIsEnabled() != null ? carouselDTO.getIsEnabled() : true);
        carousel.setCreatedAt(LocalDateTime.now());
        carousel.setUpdatedAt(LocalDateTime.now());
        carousel.setCreatedBy(createdBy);
        
        Carousel savedCarousel = carouselRepository.save(carousel);
        return convertToDTO(savedCarousel);
    }
    
    /**
     * 更新轮播图
     */
    public CarouselDTO updateCarousel(Long id, CarouselDTO carouselDTO) {
        Optional<Carousel> optionalCarousel = carouselRepository.findById(id);
        if (optionalCarousel.isPresent()) {
            Carousel carousel = optionalCarousel.get();
            carousel.setTitle(carouselDTO.getTitle());
            carousel.setDescription(carouselDTO.getDescription());
            carousel.setImageUrl(carouselDTO.getImageUrl());
            carousel.setLinkUrl(carouselDTO.getLinkUrl());
            carousel.setSortOrder(carouselDTO.getSortOrder());
            carousel.setIsEnabled(carouselDTO.getIsEnabled());
            carousel.setUpdatedAt(LocalDateTime.now());
            
            Carousel savedCarousel = carouselRepository.save(carousel);
            return convertToDTO(savedCarousel);
        }
        return null;
    }
    
    /**
     * 删除轮播图
     */
    public boolean deleteCarousel(Long id) {
        if (carouselRepository.existsById(id)) {
            carouselRepository.deleteById(id);
            return true;
        }
        return false;
    }
    
    /**
     * 切换轮播图启用状态
     */
    public CarouselDTO toggleCarouselStatus(Long id) {
        Optional<Carousel> optionalCarousel = carouselRepository.findById(id);
        if (optionalCarousel.isPresent()) {
            Carousel carousel = optionalCarousel.get();
            carousel.setIsEnabled(!carousel.getIsEnabled());
            carousel.setUpdatedAt(LocalDateTime.now());
            
            Carousel savedCarousel = carouselRepository.save(carousel);
            return convertToDTO(savedCarousel);
        }
        return null;
    }
    
    /**
     * 实体转DTO
     */
    private CarouselDTO convertToDTO(Carousel carousel) {
        return new CarouselDTO(
            carousel.getId(),
            carousel.getTitle(),
            carousel.getDescription(),
            carousel.getImageUrl(),
            carousel.getLinkUrl(),
            carousel.getSortOrder(),
            carousel.getIsEnabled(),
            carousel.getCreatedAt(),
            carousel.getUpdatedAt(),
            carousel.getCreatedBy()
        );
    }
}
